package com.calvin.study.multithread.threadlocal.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import cn.hutool.core.collection.CollectionUtil;

@RestController
@RequestMapping("/threadLocal")
public class ThreadLocalController {

	// 记录每个ip的请求次数
	private static final ThreadLocal<Map<String, Integer>> TIME_RECORD_LOCAL = ThreadLocal
			.withInitial(() -> new HashMap<String, Integer>());

	@GetMapping("/intfReqRecord")
	public @ResponseBody String record(HttpServletRequest request) {
		try {
			System.out.println(Thread.currentThread().getName());
			if (null == TIME_RECORD_LOCAL) {
				Map<String, Integer> mapp = new HashMap<>();
				mapp.put(request.getRemoteAddr(), 1);
				TIME_RECORD_LOCAL.set(mapp);
			} else {
				Map<String, Integer> map = null;
				Map<String, Integer> resMap = TIME_RECORD_LOCAL.get();
				if (CollectionUtil.isEmpty(resMap)) {
					map = new HashMap<>();
					map.put(request.getRemoteAddr(), 1);
					TIME_RECORD_LOCAL.set(map);
				} else {
					Integer num = resMap.get(request.getRemoteAddr());
					map = new HashMap<>();
					map.put(request.getRemoteAddr(), num + 1);
					TIME_RECORD_LOCAL.set(map);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			TIME_RECORD_LOCAL.remove();
		}
		return request.getRemoteAddr();
	}
}
